import type { ReactNode } from "react";
import { View, StyleSheet, Text } from "react-native";
import type { ViewStyle, TextStyle, StyleProp } from "react-native";
import { Portal, Modal, ModalProps } from "react-native-paper";
import FontIcon, { type Props as FontIconProps } from "@/components/FontIcon";

export type Props = Pick<ModalProps, "dismissable" | "visible"> & {
  /** Modal 的样式 */
  modelStyle?: StyleProp<ViewStyle>;

  /** 容器样式 */
  containerStyle?: StyleProp<ViewStyle>;

  /** 内容容器样式 */
  contentContainerStyle?: StyleProp<ViewStyle>;

  /** 标题容器样式 */
  titleContaier?: StyleProp<ViewStyle>;

  /** 标题文本样式 */
  titleTextStyle?: StyleProp<TextStyle>;

  /** 标题 */
  title?: string;

  /** 隐藏标题的元素 */
  hideTitle?: boolean;

  /** 宽度, 只能传递百分比 */
  width?: string;

  /** 子组件 */
  children?: JSX.Element | ReactNode;

  /** 标题icon组件 */
  titleIconComponent?: () => ReactNode;

  /** 标题组件 */
  titleComponent?: () => ReactNode;

  /** 点击遮罩时触发 */
  onDismiss?: () => void;
} & Pick<FontIconProps, "type" | "iconStyle">;

const Dialog = (props: Props) => {
  let iconComp;

  if (props.titleIconComponent) {
    iconComp = props.titleIconComponent();
  } else {
    iconComp = <FontIcon {...props} />;
  }

  return (
    <Portal>
      <Modal
        visible={props.visible}
        onDismiss={props.onDismiss}
        dismissable={props.dismissable}
        contentContainerStyle={[
          {
            width: props.width ? props.width : "70%",
            marginLeft: props.width ? `${(100 - parseFloat(props.width)) / 2}%` : "15%"
          },
          props.modelStyle
        ]}
      >
        <View style={[styles.container, props.containerStyle]}>
          {!props.hideTitle && (
            <View style={[styles.titleContaier, props.titleContaier]}>
              {iconComp}
              <Text style={[styles.title, props.titleTextStyle]}>{props.title}</Text>
            </View>
          )}

          <View style={props.contentContainerStyle}>{props.children}</View>
        </View>
      </Modal>
    </Portal>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#fff",
    padding: 20,
    borderRadius: 4,
    overflow: "hidden"
  },
  titleContaier: {
    flexDirection: "row",
    alignItems: "center",
  },
  title: {
    fontSize: 16,
    fontWeight: "bold"
  },
  icon: {
    fontSize: 20,
    marginRight: 4
  }
});

export default Dialog;
